<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateGameLeaderboard, fetchUpdateGameLeaderboard } from '@/service/api/games/game-leaderboard';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import DictSelect from '@/components/custom/dict-select.vue';

defineOptions({
  name: 'GameLeaderboardOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.Games.GameLeaderboard | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});


const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增游戏排行榜',
    edit: '编辑游戏排行榜'
  };
  return titles[props.operateType];
});

type Model = Api.Games.GameLeaderboardOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      userId: undefined,
      gameId: undefined,
      gameCode: '',
      bestScore: undefined,
      totalScore: undefined,
      playCount: undefined,
      totalTime: undefined,
      avgScore: undefined,
      rankType: '',
      rankPeriod: '',
      lastPlayTime: undefined,
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'rankId'
  | 'userId'
  | 'gameId'
  | 'gameCode'
  | 'rankPeriod'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  rankId: createRequiredRule('排行ID不能为空'),
  userId: createRequiredRule('用户ID不能为空'),
  gameId: createRequiredRule('游戏ID不能为空'),
  gameCode: createRequiredRule('游戏编码不能为空'),
  rankPeriod: createRequiredRule('排行周期（格式：2024-01、2024-W01、2024-01-01）不能为空'),
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { rankId, userId, gameId, gameCode, bestScore, totalScore, playCount, totalTime, avgScore, rankType, rankPeriod, lastPlayTime } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateGameLeaderboard({ userId, gameId, gameCode, bestScore, totalScore, playCount, totalTime, avgScore, rankType, rankPeriod, lastPlayTime });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateGameLeaderboard({ rankId, userId, gameId, gameCode, bestScore, totalScore, playCount, totalTime, avgScore, rankType, rankPeriod, lastPlayTime });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="120">
        <NGrid :cols="2" :x-gap="16">
          <NFormItemGi label="用户ID" path="userId">
            <NInputNumber v-model:value="model.userId" placeholder="请输入用户ID" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="游戏ID" path="gameId">
            <NInputNumber v-model:value="model.gameId" placeholder="请输入游戏ID" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="游戏编码" path="gameCode">
            <NInput v-model:value="model.gameCode" placeholder="请输入游戏编码" />
          </NFormItemGi>
          <NFormItemGi label="排行类型" path="rankType">
            <DictSelect v-model:value="model.rankType" dict-code="rank_type" placeholder="请选择排行类型" immediate />
          </NFormItemGi>
          <NFormItemGi label="最高分数" path="bestScore">
            <NInputNumber v-model:value="model.bestScore" placeholder="请输入最高分数" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="累计分数" path="totalScore">
            <NInputNumber v-model:value="model.totalScore" placeholder="请输入累计分数" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="游戏次数" path="playCount">
            <NInputNumber v-model:value="model.playCount" placeholder="请输入游戏次数" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="累计时长（秒）" path="totalTime">
            <NInputNumber v-model:value="model.totalTime" placeholder="请输入累计时长" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="平均分数" path="avgScore">
            <NInputNumber v-model:value="model.avgScore" placeholder="请输入平均分数" :step="0.01" class="w-full" />
          </NFormItemGi>
          <NFormItemGi label="最后游戏时间" path="lastPlayTime">
            <NDatePicker
              v-model:formatted-value="model.lastPlayTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              clearable
              class="w-full"
            />
          </NFormItemGi>
          <NFormItemGi :span="2" label="排行周期" path="rankPeriod">
            <NInput v-model:value="model.rankPeriod" placeholder="请输入排行周期（格式：2024-01、2024-W01、2024-01-01）" />
          </NFormItemGi>
        </NGrid>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
